package qsc.algorithm.binarysearch;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * @auther QiuShangcheng
 * @create 2021/4/15
 */
public class BinarySearch {
    private static Logger logger = (Logger) Logger.getLogger(String.valueOf(BinarySearch.class));

    public static void main(String[] args) {
        int[] arr = {1, 8, 10, 89, 1000, 1000, 1234};
        try {
            List res = binarySearch(arr, 0, arr.length - 1, 1000);
            System.out.println("index:" + res  );
        } catch (Exception e) {
//            System.out.println(e.getMessage());
            logger.info(e.getMessage());
        }

        int i = binarySearchNoRecur(arr, 10);
        System.out.println(i);
    }

    /**
     * 递归二分查找
     * @param arr
     * @param left
     * @param right
     * @param findVal
     * @return
     */
    public static List<Integer> binarySearch(int[] arr, int left, int right, int findVal) {
        ArrayList<Integer> res = new ArrayList<>();
        if (left > right) {
//            return -1;
        }
        int mid = (left + right) / 2;
        int val = arr[mid];
        if (findVal < val) {
            return binarySearch(arr, left, mid , findVal);
        } else if (findVal > val) {
            return binarySearch(arr, mid , right, findVal);
        } else {
            //实现支持对于重复数据查询
            int temp = mid;
            while (arr[--temp] == arr[mid]){
                res.add(temp);
            }
            res.add(mid);
            temp = mid;
            while (arr[++temp] == arr[mid]){
                res.add(temp);
            }
        }
        return res;
    }

    /**
     * 非递归实现二分查找
     * @param arr
     * @param target
     * @return
     */
    public static int binarySearchNoRecur(int[] arr, int target){
        int left = 0;
        int right = arr.length - 1;
        while (left <= right){
            int mid = (left + right) / 2;
            if (arr[mid] == target){
                return mid;
            }else if (arr[mid] < target){
                left = mid ;
            }else if (arr[mid] > target){
                right = mid ;
            }
        }
        return -1;
    }
}
